// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/functions/macros.h>

namespace kumo::pollux::functions::sparksql {
    template<typename T>
    struct RandFunction {
        static constexpr bool is_deterministic = false;

        template<typename TInput>
        MELON_ALWAYS_INLINE void initialize(
            const std::vector<TypePtr> & /*inputTypes*/,
            const core::QueryConfig &config,
            const TInput *seedInput) {
            const auto partitionId = config.sparkPartitionId();
            int64_t seed = seedInput ? (int64_t) *seedInput : 0;
            generator_.seed(seed + partitionId);
        }

        MELON_ALWAYS_INLINE void call(double &result) {
            result = melon::Random::randDouble01();
        }

        template<typename TInput>
        MELON_ALWAYS_INLINE void callNullable(double &result, TInput /*seedInput*/) {
            result = melon::Random::randDouble01(generator_);
        }

    private:
        std::mt19937 generator_;
    };
} // namespace kumo::pollux::functions::sparksql
